<template>
  <el-drawer
    v-model="localVisible"
    :title="`配置角色权限 - ${roleInfo.name}`"
    size="600px"
    direction="rtl"
    :before-close="handleClose"
    class="permission-drawer"
  >
    <template #header>
      <div class="drawer-header">
        <div class="header-content">
          <el-icon class="header-icon"><Setting /></el-icon>
          <div class="header-text">
            <h3 class="header-title">权限配置</h3>
            <p class="header-subtitle">为角色"{{ roleInfo.name }}"配置菜单及功能访问权限</p>
          </div>
        </div>
      </div>
    </template>

    <div class="drawer-body">
      <!-- 权限说明 -->
      <div class="permission-info">
        <div class="info-header">
          <el-icon class="info-icon"><InfoFilled /></el-icon>
          <span class="info-title">权限说明</span>
        </div>
        <div class="info-content">
          <div class="info-item">
            <el-icon color="#667eea"><Menu /></el-icon>
            <span>选择该角色可以访问的菜单页面</span>
          </div>
          <div class="info-item">
            <el-icon color="#f59e0b"><Warning /></el-icon>
            <span>选中父级菜单会自动选中所有子级菜单</span>
          </div>
        </div>
      </div>

      <!-- 权限树形结构 -->
      <div class="permission-tree">
        <div class="tree-header">
          <span class="tree-title">菜单权限</span>
          <div class="tree-actions">
            <el-button size="small" @click="handleSelectAll(menuTreeRef, menuTreeData)" class="action-btn">
              <el-icon><Select /></el-icon>
              全选
            </el-button>
            <el-button size="small" @click="handleClearAll(menuTreeRef)" class="action-btn">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>
        <el-tree
            ref="menuTreeRef"
            :data="menuTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedKeys"
            :default-expand-all="true"
            class="permission-tree-component"
            @check="handleCheck(menuTreeRef)"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon class="node-icon" :color="getNodeColor(data.level)">
                <component :is="getNodeIcon(data.level)" />
              </el-icon>
              <span class="node-label">{{ data.label }}</span>
              <el-tag :type="getTagType(data.level)" size="small" class="node-tag">
                {{ getTagLabel(data.level) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>
      <div class="permission-tree">
        <div class="tree-header">
          <span class="tree-title">权限管理</span>
          <div class="tree-actions">
            <el-button size="small" @click="handleSelectAll(permissionTreeRef, permissionTreeData)" class="action-btn">
              <el-icon><Select /></el-icon>
              全选
            </el-button>
            <el-button size="small" @click="handleClearAll(permissionTreeRef)" class="action-btn">
              <el-icon><Delete /></el-icon>
              清空
            </el-button>
          </div>
        </div>
        <el-tree
            ref="permissionTreeRef"
            :data="permissionTreeData"
            :props="treeProps"
            show-checkbox
            node-key="id"
            :default-checked-keys="checkedKeys"
            :default-expand-all="true"
            class="permission-tree-component"
            @check="handleCheck(permissionTreeRef)"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <el-icon class="node-icon" :color="getNodeColor(data.level)">
                <component :is="getNodeIcon(data.level)" />
              </el-icon>
              <span class="node-label">{{ data.label }}</span>
              <el-tag :type="getTagType(data.level)" size="small" class="node-tag">
                {{ getTagLabel(data.level) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 权限预览 -->
<!--       <div class="permission-preview">
        <div class="preview-header">
          <el-icon class="preview-icon"><View /></el-icon>
          <span class="preview-title">权限预览</span>
        </div>
        <div class="preview-content">
          <div v-if="selectedPermissions.length === 0" class="preview-empty">
            <el-icon><Warning /></el-icon>
            <span>请选择菜单权限</span>
          </div>
          <div v-else class="preview-list">
            <div class="preview-item" v-for="permission in selectedPermissions" :key="permission">
              <el-icon class="preview-item-icon" :color="getPermissionColor(permission)">
                <component :is="getPermissionIcon(permission)" />
              </el-icon>
              <span class="preview-item-label">{{ getPermissionLabel(permission) }}</span>
            </div>
          </div>
        </div>
      </div> -->
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose" class="cancel-btn">
          <el-icon><Close /></el-icon>
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" class="submit-btn">
          <el-icon><Check /></el-icon>
          {{ loading ? '保存中...' : '保存权限' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import {ref, computed, watch, nextTick, type Ref} from 'vue'
import { ElMessage } from 'element-plus'
import type { ElTree } from 'element-plus'
import {
  Setting,
  InfoFilled,
  Menu,
  Warning,
  Close,
  Check,
  Select,
  Delete,
  Document,
  Folder,
  View,
  House,
  ChatDotRound,
  Collection,
  User
} from '@element-plus/icons-vue'
import {getMenuPermission, type MenuPermission, type Permission} from "@/api/sys/permission.api.ts";
import {updateRolePermission} from "@/api/sys/role.api.ts";

interface RoleInfo {
  id: string
  name: string
  code: string
}

interface MenuNode {
  id: string
  label: string
  level: number
  icon?: string
  children?: MenuNode[]
}

interface Props {
  visible: boolean
  roleInfo: RoleInfo
  permissions: string[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', permissions: string[]): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const menuTreeRef = ref<InstanceType<typeof ElTree>>()
const permissionTreeRef = ref<InstanceType<typeof ElTree>>()
const loading = ref(false)
const checkedKeys = ref<string[]>([])
const selectedPermissions = ref<string[]>([])

// 树形组件配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 菜单树形数据 - 基于实际的 backendMenus 结构
const menuTreeData = ref<Permission[]>([])
const permissionTreeData = ref<Permission[]>([])

// 获取菜单权限
getMenuPermission('menu').then((res) => {
  menuTreeData.value = res
})
getMenuPermission('permission').then((res) => {
  permissionTreeData.value = res
})

// 本地可见性控制
const localVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听权限变化
watch(() => props.permissions, (newPermissions) => {
  checkedKeys.value = [...newPermissions]
  selectedPermissions.value = [...newPermissions]
}, { immediate: true })

// 监听抽屉显示状态
watch(() => props.visible, async (visible) => {
  if (visible) {
    await nextTick()
    // 设置选中的节点
    if (menuTreeRef.value) {
      menuTreeRef.value.setCheckedKeys(props.permissions)
    }
    if (permissionTreeRef.value) {
      permissionTreeRef.value.setCheckedKeys(props.permissions)
    }
  }
})

// 获取节点颜色
const getNodeColor = (level: number) => {
  switch (level) {
    case 1: return '#667eea'
    case 2: return '#10b981'
    default: return '#6b7280'
  }
}

// 获取节点图标
const getNodeIcon = (level: number) => {
  switch (level) {
    case 1: return Menu
    case 2: return Document
    default: return Folder
  }
}

// 获取标签类型
const getTagType = (level: number) => {
  switch (level) {
    case 1: return 'primary'
    case 2: return 'success'
    default: return 'info'
  }
}

// 获取标签文本
const getTagLabel = (level: number) => {
  switch (level) {
    case 1: return '一级菜单'
    case 2: return '二级菜单'
    default: return '菜单'
  }
}

// 处理树形组件选择变化
const handleCheck = (ref: InstanceType<typeof ElTree>) => {
  if (ref) {
    const checkedNodes = ref.getCheckedKeys()
    const halfCheckedNodes = ref.getHalfCheckedKeys()
    selectedPermissions.value = [...checkedNodes, ...halfCheckedNodes] as string[]
  }
}

// 获取权限颜色
const getPermissionColor = (permission: string) => {
  const menuMap: Record<string, string> = {
    'dashboard': '#667eea',
    'user-permission': '#10b981',
    'chat': '#f59e0b',
    'knowledge-plus': '#8b5cf6',
    'knowledge-graph': '#06b6d4',
    'personal-knowledge': '#84cc16',
    'recent-chats-parent': '#f97316'
  }
  return menuMap[permission] || '#6b7280'
}

// 获取权限图标
const getPermissionIcon = (permission: string) => {
  const iconMap: Record<string, any> = {
    'dashboard': House,
    'user-permission': User,
    'chat': ChatDotRound,
    'knowledge-plus': Collection,
    'knowledge-graph': Menu,
    'personal-knowledge': Folder,
    'recent-chats-parent': Document
  }
  return iconMap[permission] || Menu
}

// 获取权限标签
const getPermissionLabel = (permission: string) => {
  const labelMap: Record<string, string> = {
    'dashboard': '首页',
    'user-permission': '角色管理',
    'chat': '智库问答',
    'knowledge-plus': '智库+',
    'chart-query': '图表查询',
    'result-matching': '成果匹配',
    'translation-assistant': '翻译助手',
    'ocr-recognition': '图文识别',
    'doc-assistant': '文档助手',
    'solution-assistant': '标书助手',
    'knowledge-graph': '知识图谱',
    'personal-knowledge': '个人知识库',
    'recent-chats-parent': '近期对话',
    'pipeline-construction': '管道施工',
    'pipeline-maintenance': '管道维修',
    'welding-construction': '焊接施工注意',
    'recent-chats': '查看更多'
  }
  return labelMap[permission] || permission
}

// 全选
const handleSelectAll = (ref: InstanceType<typeof ElTree>, data: Permission[]) => {
  console.debug(ref)
  if (ref) {
    const allKeys = getAllNodeKeys(data)
    ref.setCheckedKeys(allKeys)
    selectedPermissions.value = allKeys
  }
}

// 清空
const handleClearAll = (ref: InstanceType<typeof ElTree>) => {
  if (ref) {
    ref.setCheckedKeys([])
    selectedPermissions.value = []
  }
}

// 获取所有节点的key
const getAllNodeKeys = (nodes: Permission[]): string[] => {
  const keys: string[] = []
  const traverse = (nodeList: Permission[]) => {
    nodeList.forEach(node => {
      keys.push(node.id)
      if (node.children) {
        traverse(node.children)
      }
    })
  }
  traverse(nodes)
  return keys
}

// 提交权限配置
const handleSubmit = async () => {
  if (!menuTreeRef.value && !permissionTreeRef.value) return

  try {
    loading.value = true
    
    // 获取选中的节点（包括半选中的父节点）
    const menuTreeCheckedNodes = menuTreeRef.value.getCheckedKeys()
    // 未全选节点不传入，否则会导致子节点全选中
    // const menuTreeHalfCheckedNodes = menuTreeRef.value.getHalfCheckedKeys()
    const permissionTreeCheckedNodes = permissionTreeRef.value.getCheckedKeys()
    // const permissionTreeHalfCheckedNodes = permissionTreeRef.value.getHalfCheckedKeys()
    const allSelectedKeys = [...menuTreeCheckedNodes, ...permissionTreeCheckedNodes] as string[]

    updateRolePermission(props.roleInfo.id, allSelectedKeys).then(res => {
      emit('submit', res)
      ElMessage.success('权限配置已保存')
    })
  } catch (error) {
    console.error('保存权限失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('cancel')
  localVisible.value = false
}
</script>

<style scoped>
/* 抽屉整体样式 */
.permission-drawer :deep(.el-drawer) {
  background: #f8fafc;
}

.permission-drawer :deep(.el-drawer__header) {
  padding: 0 !important;
  margin: 0 !important;
  margin-bottom: 0 !important;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  min-height: auto;
}

.permission-drawer :deep(.el-drawer .el-drawer__header) {
  margin-bottom: 0 !important;
}

.permission-drawer :deep(.el-drawer__container .el-drawer__header) {
  margin-bottom: 0 !important;
}

.permission-drawer :deep(.el-drawer__body) {
  padding: 0;
}

.permission-drawer :deep(.el-drawer__footer) {
  padding: 0 !important;
  margin: 0 !important;
  border-top: 1px solid #e5e7eb;
}

.permission-drawer :deep(.el-drawer .el-drawer__footer) {
  padding: 0 !important;
  margin: 0 !important;
}

.permission-drawer :deep(.el-drawer__container .el-drawer__footer) {
  padding: 0 !important;
  margin: 0 !important;
}

.permission-drawer :deep(.el-drawer__close-btn) {
  font-size: 20px;
  top: 16px;
  right: 16px;
}

.permission-drawer :deep(.el-drawer__close-btn:hover) {
  color: rgba(255, 255, 255, 0.8);
}

/* 抽屉头部样式 */
.drawer-header {
  padding: 16px 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 28px;
}

.header-text {
  flex: 1;
}

.header-title {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
}

/* 抽屉主体样式 */
.drawer-body {
  padding: 16px 20px;
  background: #f8fafc;
  height: 100%;
  overflow-y: auto;
}

/* 权限信息样式 */
.permission-info {
  background: white;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}

.info-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  padding-bottom: 6px;
  border-bottom: 1px solid #e5e7eb;
}

.info-icon {
  font-size: 16px;
  color: #667eea;
}

.info-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #6b7280;
  line-height: 1.5;
}

/* 权限树样式 */
.permission-tree {
  background: white;
  border-radius: 12px;
  padding: 12px 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}

.tree-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.tree-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.tree-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 6px;
}

.permission-tree-component {
  background: transparent;
}

.permission-tree-component :deep(.el-tree-node__content) {
  height: 32px;
  border-radius: 6px;
  margin-bottom: 1px;
  transition: all 0.2s;
}

.permission-tree-component :deep(.el-tree-node__content:hover) {
  background: #f3f4f6;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.node-icon {
  font-size: 14px;
}

.node-label {
  flex: 1;
  font-size: 14px;
  color: #374151;
}

.node-tag {
  font-size: 10px;
  height: 18px;
  line-height: 16px;
  border-radius: 4px;
}

/* 权限预览样式 */
.permission-preview {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.preview-icon {
  font-size: 16px;
  color: #667eea;
}

.preview-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.preview-content {
  max-height: 200px;
  overflow-y: auto;
}

.preview-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 20px;
  color: #9ca3af;
  font-size: 13px;
}

.preview-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.preview-item-icon {
  font-size: 14px;
}

.preview-item-label {
  font-size: 13px;
  color: #374151;
}

/* 抽屉底部样式 */
.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 12px 20px;
  background: white;
}

.cancel-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  background: #f1f5f9;
  border: 1px solid #d1d5db;
  color: #6b7280;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
  transform: translateY(-1px);
}

.submit-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-drawer :deep(.el-drawer) {
    width: 100% !important;
  }

  .drawer-header {
    padding: 12px 16px;
  }

  .drawer-body {
    padding: 12px 16px;
  }

  .tree-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .tree-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .drawer-footer {
    padding: 12px 16px;
    flex-direction: column;
    gap: 8px;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .permission-drawer :deep(.el-drawer) {
    width: 100% !important;
  }

  .tree-actions {
    flex-direction: column;
    gap: 8px;
  }

  .action-btn {
    width: 100%;
  }
}
</style>

<style>
/* 全局样式覆盖 - 针对权限配置抽屉 */
.permission-drawer .el-drawer__header {
  margin-bottom: 0 !important;
  padding: 0 !important;
}

.permission-drawer .el-drawer__body {
  padding: 0 !important;
}

.permission-drawer .el-drawer__footer {
  padding: 0 !important;
  margin: 0 !important;
}

/* 更强的选择器优先级 */
.el-drawer.permission-drawer .el-drawer__footer {
  padding: 0 !important;
  margin: 0 !important;
}

.el-drawer.permission-drawer .el-drawer__header {
  margin-bottom: 0 !important;
  padding: 0 !important;
}

.el-drawer.permission-drawer .el-drawer__body {
  padding: 0 !important;
}
</style>
